package com.zhipu.balance.pop

import android.os.Environment
import android.widget.Button
import android.widget.TextView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.core.CenterPopupView
import com.zhipu.balance.R
import com.zhipu.balance.listener.AddOnClickListener
import com.zhipu.balance.mobile.temporaryClass.VersionUpdate
import com.zhipu.balance.utils.ApkController
import com.zhipu.balance.utils.CommonUtils
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.view.NumberProgressBar
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import okhttp3.Call
import java.io.File


class UpdatePopup(var mVersionUpdate : VersionUpdate) : CenterPopupView(ActivityUtils.getTopActivity()){


    private var mNumberProgressBar: NumberProgressBar? = null
    private var mBtnOk : Button? = null

    override fun getImplLayoutId(): Int {
        return R.layout.popup_updata
    }


    override fun onCreate() {
        super.onCreate()
        findViewById<TextView>(R.id.tv_title).text = "是否升级到${mVersionUpdate.versionName}版本?"
        findViewById<TextView>(R.id.tv_update_info).text = mVersionUpdate.explain
        mNumberProgressBar = findViewById(R.id.NumberProgressBar)
        mBtnOk = findViewById(R.id.BtnOk)
        mBtnOk?.setOnClickListener {
            mBtnOk?.visibility = GONE
            mNumberProgressBar?.visibility = VISIBLE
            val appDir = File(Environment.getExternalStorageDirectory().absolutePath)
            if (!appDir.exists()) {
                appDir.mkdirs()
            }
            val appPath = appDir.toString() + File.separator + "Balance/APP/"
            val fileNam  = CommonUtils.getApkName()
            download(mVersionUpdate.url, appPath, fileNam, object : AddOnClickListener {
                override fun onSkipClicked(sKip: String?) {
                    if (sKip == "下载失败") {
                        mBtnOk?.setVisibility(VISIBLE)
                        mNumberProgressBar?.setVisibility(GONE)
                    }else{
                        dismiss()
                        InitializeUtils.getDefaultMaker()?.show("正在安装")
                        Thread{
                            val path = appPath + fileNam;
                            if (ApkController.install(path, context)) {
                                InitializeUtils.getDefaultMaker()?.show("安裝成功")
                            } else {
                                InitializeUtils.getDefaultMaker()?.show("安裝失败")
                            }
                        }.start()
//                        AppUtils.installApp(appPath + fileNam)
                    }
                }
            })
        }
    }


    /**
     * 下载
     * @param url 下载地址
     * @param path 文件保存路径
     * @param fileName 文件名称
     * @param addOnClickListener 回调
     */
    private fun download(url: String?, path: String?, fileName: String?, addOnClickListener: AddOnClickListener?) {
        OkHttpUtils.get().url(url).build().execute(object : FileCallBack(path, fileName) {
            override fun inProgress(progress: Float, total: Long, id: Int) {
                setNumberProgressBar(progress)
                super.inProgress(progress, total, id)
            }

            override fun onError(call: Call?, e: java.lang.Exception?, id: Int) {
                addOnClickListener?.onSkipClicked("下载失败")
            }


            override fun onResponse(response: File, id: Int) {
                ToastUtils.make().show("下载完成")
                LogUtils.d(response.parent)
                addOnClickListener?.onSkipClicked("下载完成")
            }
        })
    }


    /**
     * 设置进度
     */
    fun setNumberProgressBar(progress: Float) {
        if (null != mNumberProgressBar) {
            mNumberProgressBar?.progress = Math.round(progress * 100)
            mNumberProgressBar?.max = 100
        }
    }
}